package com.zhiyou.app.shop.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;

import com.zhiyou.app.shop.common.AycshopException;

public class FileUtil {
	private static final int BUFFER_SIZE = 16 * 1024;
	private static Log log = org.apache.commons.logging.LogFactory
			.getLog(FileUtil.class);

	public static final String getUserId() {
		return new String("id");
	}

	/**
	 * 根据传入的路径，新建文件夹,path为需要建立的文件夹
	 */
	public static boolean newFolder(String path) {
		String sPath = path;
		sPath = sPath.toString();// 中文转换
		// 创建一个File(文件）对象
		File myFilePath = new File(sPath);
		if (!myFilePath.exists()) {
			try {
				myFilePath.mkdirs();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		} else
			return false;
	}

	/**
	 * 获得系统的真实路径
	 * 
	 * @return
	 */
	public static String getRealPahtFromWebPath() {
		String classPath = FileUtil.class.getResource("").getPath().substring(1);
		int replaceInt = classPath.indexOf("/WEB-INF/classes/");
		String replaceStr = classPath.substring(replaceInt);
		String path = StringUtils.remove(classPath, replaceStr);
		return "/" + path;
	}

	/**
	 * copy文件到目的文件夹
	 * @param srcFile 源文件
	 * @param destFile 目标文件
	 */
	public static void copyFile(File srcFile, String destFile) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
				out.write(buffer, 0, len);
			}
		}catch(IOException e){
			throw new RuntimeException(e);
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 递归删除指定目录下的所有文件
	 */
	public static void deleteFiles(File fileDir) throws RuntimeException {
		// 判断文件是否为目录
		if (fileDir.isDirectory()) {
			// 得到目录下面的所有文件列表，包括文件夹
			File[] files = fileDir.listFiles();
			// 得到文件个数，包括文件夹
			int count = files.length;

			// 删除目录下的所有文件及文件夹
			for (int i = 0; i < count; i++) {
				// 判断文件是否为目录，若是目录责递归调用目录删除，若是文件则直接删除
				if (files[i].isDirectory()) {
					deleteFiles(files[i]);
				} else {
					// 删除文件
					files[i].delete();
				}
			}

			// 删除目录本身
			fileDir.delete();
		} else {
			// 删除文件本身
			if (fileDir.exists())
				fileDir.delete();
		}
	}

	/**
	 * 上传文件
	 * @param fileName 文件名称
	 * @param file 文件对象
	 * @param dir 目标路径
	 * @param allowTypes 允许文件类型
	 * @return 上传到系统上的文件的绝对路径
	 */
	public static String uploadFile(String fileName, File file, String dir, String allowTypes, int allowLength) {
		if (!checkFileType(fileName, allowTypes)) {
			String[] params = {fileName};
			throw new AycshopException("shopManage.imgType.invalidate", params);
		}
		if((file.length()/1024) > allowLength){
			String[] params = {String.valueOf(file.length()/1024)};
			throw new AycshopException("shopManage.imgLeng.invalidate", params);
		}
		//目标文件夹如果不存在
		File destDir = new File(dir);
		if(!destDir.exists()){
			destDir.mkdirs();
		}
		// 重命名文件
		if (fileName != null) {
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
			fileName = System.currentTimeMillis() + "." + fileType;
		}
		String targetFile = dir.endsWith("/") ? dir+fileName : dir+"/"+fileName;
		FileUtil.copyFile(file, targetFile);
		return targetFile;
	}
	
	
	
	
	/**
	 * 验证文件扩展名
	 * 
	 * @param fileName
	 * @return
	 */
	private static boolean checkFileType(String fileName, String allowTypes) {
		String[] types = allowTypes.split(",");
		if (fileName != null && !"".equals(fileName)) {
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
			for (String type : types) {
				if (type.equalsIgnoreCase(fileType)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * aycshop 图片上传
	 * @param tmpFile struts2生成的临时文件
	 * @param fileName 上传文件的名称
	 * @param secDir 二级目录
	 * @return
	 */
	public static String aycShopUpload(File tmpFile, String fileName, String secDir){
		String basePath = PropertiesUtil.getSysProperties("upload.img.basepath")+"/";
		String destPath = basePath+secDir+"/";
		String allowTypes = PropertiesUtil.getSysProperties("img.type.allow");
		String allowLength = PropertiesUtil.getSysProperties("img.length.allow");
		int alength = Integer.valueOf(allowLength);
		String absPath = FileUtil.uploadFile(fileName, tmpFile, destPath, allowTypes,alength);
		return absPath.substring(basePath.length());
	}
	/**
	 * 下载方法
	 * 
	 * @param response
	 * @param attachFile
	 *            文件全路径+全名(服务器端的URL)
	 * @param fileName
	 *            用户另存为的文件名
	 * @throws java.io.IOException
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static void downLoadFile(final HttpServletRequest request,
			final HttpServletResponse response, String attachFile,
			String fileName) throws UnsupportedEncodingException, IOException {
		String range = request.getHeader("RANGE");
		long skip = 0;
		if (range != null && !"".equals(range)) {
			range = range.toLowerCase();
			if (range.startsWith("bytes")) {
				int equotPos = range.indexOf("=");
				int toPos = range.indexOf("-");
				if (toPos < 0 && equotPos > 0) {
					toPos = range.length();
				}
				if (equotPos > 0 && toPos > 0) {
					skip = Long.parseLong(range.substring(equotPos + 1, toPos).trim());
				}
			}
		}
		File file = new File(attachFile);
		// fileName = safeFileName(fileName);
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Accept-Ranges", "bytes");
		response.setHeader("Accept-Charset", "UTF-8");
		response.setHeader("Content-type", "application/octet-stream");
		if (skip == 0) {
			response.setHeader("Content-Length", String.valueOf(file.length()));
			response.setStatus(HttpServletResponse.SC_OK);
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		} else {
			response.setHeader("Content-Length", String.valueOf(file.length()- skip));
			response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
			response.setHeader("Content-Range", "bytes " + skip + "-"+ (file.length() - 1) + "/" + file.length());
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		if (!file.exists()) {
			response.sendError(404);
			return;
		}
		// long totalRead = 0;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());

			byte[] buff = new byte[8192];
			int bytesRead;
			if (skip > 0) {
				bis.skip(skip);
			}
			// org.apache.catalina.servlets.DefaultServlet
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				bis.close();
			}

			if (bos != null) {
				bos.close();
			}
		}
	}

}
